from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect, csrf_exempt

from .models import Category
from .forms import CategoryForm, CategoryModelForm


# def add(request):  # get post
#     if request.method == 'GET':
#         return render(request, 'category/add.html')
#     else:
#         name = request.POST.get('name')
#         desc = request.POST.get('desc')
#         Category.objects.create(name=name, desc=desc)
#         return HttpResponse('success')


# def add(request):  # get post
#     if request.method == 'GET':
#         form = CategoryForm()
#         return render(request, 'category/add.html', {'form': form})
#     else:
#         form = CategoryForm(request.POST)
#         if form.is_valid():
#             # 保存数据
#             name = form.cleaned_data['name']
#             desc = form.cleaned_data['desc']
#             Category.objects.create(name=name, desc=desc)
#             return HttpResponse('success')
#         else:
#             return render(request, 'category/add.html', {'form': form})
#         return HttpResponse('success')


def add(request):  # get post
    if request.method == 'GET':
        form = CategoryModelForm()
        return render(request, 'category/add.html', {'form': form})
    else:
        form = CategoryModelForm(request.POST)
        if form.is_valid():
            # 保存数据
            form.save()
            return HttpResponse('success')
        else:
            return render(request, 'category/add.html', {'form': form})
        return HttpResponse('success')

# 防止别人随便提交表单，有多重处理方式可以去完成csrf验证或者跳过
# 验证的话：在表单中添加{% csrf_token %}的标签
# 跳过1： 通过在settings中注释中间件'django.middleware.csrf.CsrfViewMiddleware',
# 跳过2:  使用csrf_exempt装饰器
